package com.lang.downloader.http.config;

import com.alibaba.fastjson.annotation.JSONCreator;
import com.alibaba.fastjson.annotation.JSONField;
import com.lang.DownloadConfig;
import com.lang.downloader.http.exception.HttpDownloadException;
import com.lang.downloader.http.header.HttpRequestHeader;
import com.lang.downloader.http.header.HttpResponseHeader;
import com.lang.util.FileSize;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.OutputStream;
import java.io.Serializable;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Getter
@Setter
public class HttpDownloadConfig extends DownloadConfig implements Serializable {
    /**
     * 已下载的数据量
     */
    private AtomicLong hasDone = new AtomicLong();
    /**
     * 文件大小
     */
    private Long contentLength;
    /**
     * 请求头
     */
    private HttpRequestHeader requestHeader = HttpRequestHeader.defaultHeader();
    /**
     * 响应头
     */
    private HttpResponseHeader responseHeader = new HttpResponseHeader();
    /**
     * 单链接下载最大文件
     * 太大将多线程下载 提高速度
     */
    private Long fileMaxSize = FileSize.MB(10L);
    /**
     * 最大下载时长
     */
//    @JSONField(serializeUsing = DurationJsonSerializeUsing.class, deserializeUsing = DurationJsonDeserializeUsing.class)
    private Duration totalDownloadTime = Duration.ofDays(2);
    /**
     * 多线程下载时的核心线程数
     */
    private Integer corePoolSize = 3;
    /**
     * 当分片下载时，有效
     */
    private List<CacheFile> tempFiles;

    /**
     * 下载文件输出流
     */
    private transient OutputStream outputStream;

    @JSONCreator
    public HttpDownloadConfig(@JSONField(name = "url") String url,
                              @JSONField(name = "savePath") String savePath,
                              @JSONField(name = "tempDir") String tempDir,
                              @JSONField(name = "configFilePath") String configFilePath) {
        if (StringUtils.isBlank(url))
            throw new HttpDownloadException("请求链接不能为空");
        if (StringUtils.isBlank(savePath))
            throw new HttpDownloadException("文件保存路径不能为空");
        if (StringUtils.isBlank(tempDir)) {
            tempDir = savePath + "temp";
        }
        if (StringUtils.isBlank(configFilePath)) {
            configFilePath = savePath + ".config";
        }
        this.setTempDir(tempDir);
        this.setConfigFilePath(configFilePath);
        this.setUrl(url);
        this.setSavePath(savePath);
    }
}
